package com.zscat.mallplus.util;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.*;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * httpclient请求工具类
 *
 * @描述：
 * @program: drivermanage
 * @Date: 2018/8/3 10:48
 * @Author: zengyao
 * @Description:
 */
public class HttpClientUtil {
    /**
     * 最大线程池
     */
    public static final int THREAD_POOL_SIZE = 5;

    public interface HttpClientDownLoadProgress {
        public void onProgress(int progress);
    }

    private static HttpClientUtil httpClientDownload;

    private ExecutorService downloadExcutorService;

    private HttpClientUtil() {
        downloadExcutorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
    }

    public static HttpClientUtil getInstance() {
        if (httpClientDownload == null) {
            httpClientDownload = new HttpClientUtil();
        }
        return httpClientDownload;
    }

    public void download(final String url, final String filePath, final Map<String, String> headMap, final Map<String, String> params) {
//        downloadExcutorService.execute(new Runnable() {
//
//            @Override
//            public void run() {
        httpDownloadFile(url, filePath, null, headMap, params);
//            }
//        });
    }

    public void download(final String url, final String filePath,
                         final HttpClientDownLoadProgress progress, final Map<String, String> headMap, final Map<String, String> params) {
//        downloadExcutorService.execute(new Runnable() {
//
//            @Override
//            public void run() {
        httpDownloadFile(url, filePath, progress, headMap, params);
//            }
//        });
    }

    /**
     * 下载文件
     *
     * @param url
     * @param filePath
     */
    private void httpDownloadFile(String url, String filePath,
                                  HttpClientDownLoadProgress progress, Map<String, String> headMap, Map<String, String> params) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpPost httpPost = new HttpPost(url);
//            httpPost.setProtocolVersion(HttpVersion.HTTP_1_0);
            setPostHead(httpPost, headMap);
            setPostParams(httpPost, params);
            CloseableHttpResponse response1 = httpclient.execute(httpPost);
            try {
                System.out.println(response1.getStatusLine());
                HttpEntity httpEntity = response1.getEntity();
                long contentLength = httpEntity.getContentLength();
                InputStream is = httpEntity.getContent();
                // 根据InputStream 下载文件
                ByteArrayOutputStream output = new ByteArrayOutputStream();
                byte[] buffer = new byte[4096];
                int r = 0;
                long totalRead = 0;
                while ((r = is.read(buffer)) > 0) {
                    output.write(buffer, 0, r);
                    totalRead += r;
                    if (progress != null) {// 回调进度
                        progress.onProgress((int) (totalRead * 100 / contentLength));
                    }
                }
                FileOutputStream fos = new FileOutputStream(filePath);
                output.writeTo(fos);
                output.flush();
                output.close();
                fos.close();
                EntityUtils.consume(httpEntity);
            } finally {
                response1.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * get请求
     *
     * @param url
     * @return
     */
    public String httpGet(String url) {
        return httpGet(url, null);
    }

    public String httpGetImage(String url, Map<String, String> headMap, String destLocation) {
        String responseContent = null;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpGet httpGet = new HttpGet(url);
            setGetHead(httpGet, headMap);
            CloseableHttpResponse response1 = httpclient.execute(httpGet);
            try {
//                System.out.println(response1.getStatusLine());
                if (HttpStatus.SC_OK == response1.getStatusLine().getStatusCode()) {
                    HttpEntity entity = response1.getEntity();
                    byte[] b = EntityUtils.toByteArray(entity);
                    FileOutputStream fos = new FileOutputStream(destLocation);
                    fos.write(b);
                    fos.close();
                    EntityUtils.consume(entity);
                    responseContent = destLocation;
                }
            } finally {
                response1.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseContent;
    }

    /**
     * http get请求
     *
     * @param url
     * @return
     */
    public String httpGet(String url, Map<String, String> headMap) {
        String responseContent = null;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpGet httpGet = new HttpGet(url);
            setGetHead(httpGet, headMap);
            CloseableHttpResponse response1 = httpclient.execute(httpGet);
            try {
                HttpEntity entity = response1.getEntity();
                responseContent = getRespString(entity);
//                System.out.println("请求返回内容:" + responseContent);
                EntityUtils.consume(entity);
            } finally {
                response1.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseContent;
    }

    public String httpPost(String url, Map<String, String> paramsMap) {
        return httpPost(url, paramsMap, null);
    }

    /**
     * http的post请求
     *
     * @param url
     * @param paramsMap
     * @return
     */
    public String httpPost(String url, Map<String, String> paramsMap,
                           Map<String, String> headMap) {
        String responseContent = null;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpPost httpPost = new HttpPost(url);
            setPostHead(httpPost, headMap);
            setPostParams(httpPost, paramsMap);
            CloseableHttpResponse response = httpclient.execute(httpPost);
            try {
//                System.out.println(response.getStatusLine());
                HttpEntity entity = response.getEntity();
                responseContent = getRespString(entity);
                EntityUtils.consume(entity);
            } finally {
                response.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
//        System.out.println("responseContent = " + responseContent);
        return responseContent;
    }

    /**
     * 设置POST的参数
     *
     * @param httpPost
     * @param paramsMap
     * @throws Exception
     */
    private void setPostParams(HttpPost httpPost, Map<String, String> paramsMap)
            throws Exception {
        if (paramsMap != null && paramsMap.size() > 0) {
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            Set<String> keySet = paramsMap.keySet();
            for (String key : keySet) {
                nvps.add(new BasicNameValuePair(key, paramsMap.get(key)));
            }
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
        }
    }

    /**
     * 设置http的HEAD
     *
     * @param httpGet
     * @param headMap
     */
    private void setGetHead(HttpGet httpGet, Map<String, String> headMap) {
        if (headMap != null && headMap.size() > 0) {
            Set<String> keySet = headMap.keySet();
            for (String key : keySet) {
                httpGet.addHeader(key, headMap.get(key));
            }
        }
    }

    /**
     * 设置http的HEAD
     *
     * @param httpPost
     * @param headMap
     */
    private void setPostHead(HttpPost httpPost, Map<String, String> headMap) {
        if (headMap != null && headMap.size() > 0) {
            Set<String> keySet = headMap.keySet();
            for (String key : keySet) {
                httpPost.addHeader(key, headMap.get(key));
            }
        }
    }

    /**
     * 上传文件
     *
     * @param serverUrl       服务器地址
     * @param localFilePath   本地文件路径
     * @param serverFieldName
     * @param params
     * @return
     * @throws Exception
     */
    public String uploadFileImpl(String serverUrl, String localFilePath,
                                 String serverFieldName, Map<String, String> params, Map<String, String> headMap)
            throws Exception {
        String respStr = null;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpPost httppost = new HttpPost(serverUrl);
            setPostHead(httppost, headMap);
            FileBody binFileBody = new FileBody(new File(localFilePath));

            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder
                    .create();
            // add the file params
            multipartEntityBuilder.addPart(serverFieldName, binFileBody);
            // 设置上传的其他参数
            setUploadParams(multipartEntityBuilder, params);

            HttpEntity reqEntity = multipartEntityBuilder.build();

            httppost.setEntity(reqEntity);

            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                System.out.println(response.getStatusLine());
                HttpEntity resEntity = response.getEntity();
                respStr = getRespString(resEntity);
                EntityUtils.consume(resEntity);
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
        System.out.println("resp=" + respStr);
        return respStr;
    }


    /**
     * 设置上传文件时所附带的其他参数
     *
     * @param multipartEntityBuilder
     * @param params
     */
    private void setUploadParams(MultipartEntityBuilder multipartEntityBuilder,
                                 Map<String, String> params) {
        if (params != null && params.size() > 0) {
            Set<String> keys = params.keySet();
            for (String key : keys) {
                multipartEntityBuilder
                        .addPart(key, new StringBody(params.get(key),
                                ContentType.TEXT_PLAIN));
            }
        }
    }

    /**
     * 将返回结果转化为String
     *
     * @param entity
     * @return
     * @throws Exception
     */
    private String getRespString(HttpEntity entity) throws Exception {
        if (entity == null) {
            return null;
        }
        InputStream is = entity.getContent();
        StringBuffer strBuf = new StringBuffer();
        byte[] buffer = new byte[4096];
        int r = 0;
        while ((r = is.read(buffer)) > 0) {
            strBuf.append(new String(buffer, 0, r, "UTF-8"));
        }
        return strBuf.toString();
    }

    private HttpClient client;

    public String sendXMLDataByPost(String url, String xmlData) throws Exception {
        if (client == null) {
            client = HttpClients.createDefault();
        }
        HttpPost post = new HttpPost(url);
        List<BasicNameValuePair> parameters = new ArrayList<>();
        parameters.add(new BasicNameValuePair("xml", xmlData));
        post.setEntity(new UrlEncodedFormEntity(parameters, "UTF-8"));
        HttpResponse response = client.execute(post);
        System.out.println(response.toString());
        HttpEntity entity = response.getEntity();
        String result = EntityUtils.toString(entity, "UTF-8");
        return result;
    }

    public static String httpPostMultipartForm() {
        StringBuffer buffer = new StringBuffer();
        try {
            MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, "----------ThIs_Is_tHe_bouNdaRY_$", Charset.defaultCharset());
            multipartEntity.addPart("phone", new StringBody("136********", Charset.forName("UTF-8")));
            multipartEntity.addPart("receiver", new StringBody("138***********", Charset.forName("UTF-8")));
            multipartEntity.addPart("image", new FileBody(new File(System.getProperty("user.dir") + "/src/test/resources/123.jpg"), "image/png"));

            HttpPost request = new HttpPost("http://xxxxx.do");
            request.setEntity(multipartEntity);
            request.addHeader("Content-Type", "multipart/form-data; boundary=----------ThIs_Is_tHe_bouNdaRY_$");

            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpResponse response = httpClient.execute(request);

            InputStream is = response.getEntity().getContent();
            BufferedReader in = new BufferedReader(new InputStreamReader(is));
            String line = "";
            while ((line = in.readLine()) != null) {
                buffer.append(line);
            }
            System.out.println("发送消息收到的返回：" + buffer.toString());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return buffer.toString();
    }

    public String getXMLString() {
//        String XML_HEADER = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
        StringBuffer sb = new StringBuffer();
//        sb.append(XML_HEADER);
        sb.append("<xml>");
        sb.append("<AppId>123456</AppId>");
        sb.append("<CreateTime>123456</CreateTime>");
        sb.append("<InfoType>component_verify_ticket</InfoType>");
        sb.append("<ComponentVerifyTicket>11111111</ComponentVerifyTicket>");
        sb.append("</xml>");
        return sb.toString();
    }

    public static String getLoginSessionId() {
        HttpClientUtil client = HttpClientUtil.getInstance();
        Map<String, String> headers = new HashMap<String, String>();
        try {
//            CookieStore cookieStore = new BasicCookieStore();
//            httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
//            httpGet = new HttpGet("https://hn.122.gov.cn/m/login?t=2");
//            headers.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
//            headers.put("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36");
//            String result = client.httpGet("https://hn.122.gov.cn/m/login?t=2");
//            String JSESSIONID = null;
//            List<Cookie> cookies = cookieStore.getCookies();
//            for (int i = 0; i < cookies.size(); i++) {
//                System.out.println(cookies.get(i).getName() + "=" + cookies.get(i).getValue());
//                if (cookies.get(i).getName().equals("JSESSIONID-L")) {
//                    JSESSIONID = cookies.get(i).getValue();
//                    break;
//                }
//            }
//            return JSESSIONID;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "";
    }

    public static String downloadVeriCode(String jsessionId) {
        HttpClientUtil client = HttpClientUtil.getInstance();
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Cookie", "JSESSIONID-L=" + jsessionId);
        headers.put("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36");
        headers.put("Accept", "image/webp,image/*,*/*;q=0.8");
        headers.put("Accept-Language", "zh-CN");
        String url = "https://hn.122.gov.cn/m/tmri/captcha/math?nocache=1557906028876";
        String destLocation = "D:\\vericode\\" + System.currentTimeMillis() + ".jpg";
        client.httpGetImage(url, headers, destLocation);
        return destLocation;
    }

    public static String checkkey(String jsessionId, String vericode) {
        HttpClientUtil client = HttpClientUtil.getInstance();
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36");
        headers.put("Cookie", "JSESSIONID-L=" + jsessionId);
        String url = "https://hn.122.gov.cn/user/m/login/checkkey";
        Map<String, String> params = new HashMap<>();
        params.put("usertype", "2");
        params.put("systemid", "main");
        params.put("ticket", "");
        params.put("szzsid", "0c7efb90dcea4f736a929a6489ee3930");
        params.put("username", "43011803005087");
        params.put("password", "d2FudG9uZzg4OA==");
        params.put("csessionid", vericode);
        String result = client.httpPost(url, params, headers);
        return result;
    }

    /**
     * 绕过验证
     *
     * @return
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     */
    public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
        SSLContext sc = SSLContext.getInstance("SSLv3");

        // 实现一个X509TrustManager接口，用于绕过验证，不用修改里面的方法
        X509TrustManager trustManager = new X509TrustManager() {
            @Override
            public void checkClientTrusted(
                    java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                    String paramString) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(
                    java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                    String paramString) throws CertificateException {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };

        sc.init(null, new TrustManager[]{trustManager}, null);
        return sc;
    }


    public static String getLoginTicket(String message) throws KeyStoreException, FileNotFoundException {
        HttpClientUtil client = HttpClientUtil.getInstance();


        Map<String, String> headers = new HashMap<String, String>();
        headers.put("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36");
        headers.put("Content-Type", "application/x-www-form-urlencoded");
        String url = "https://127.0.0.1:53015/ia300";
        Map<String, String> params = new HashMap<>();
        String json = "{\"function\":\"IA300SHA1WithSeedEx\", \"Seed\":\"" + message + "\"}";
        params.put("json", json);
//        params.put("function", "IA300SHA1WithSeedEx");
//        params.put("Seed", message);
        String result = client.httpPost(url, params, headers);
        return result;
    }

    public static String checkLogin(String jsessionId, String ticket, String vericode) {
        HttpClientUtil client = HttpClientUtil.getInstance();
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36");
        headers.put("Cookie", "JSESSIONID-L=" + jsessionId);
        String url = "https://hn.122.gov.cn/user/m/loginkey";
        Map<String, String> params = new HashMap<>();
        params.put("usertype", "2");
        params.put("systemid", "main");
        params.put("ticket", ticket);
        params.put("szzsid", "0c7efb90dcea4f736a929a6489ee3930");
        params.put("username", "43011803005087");
        params.put("password", "d2FudG9uZzg4OA==");
        params.put("csessionid", vericode);
        String result = client.httpPost(url, params, headers);
        return result;
    }

    public String getJSessionId(String url, Map<String, String> headMap) {
        CloseableHttpClient httpClient = null;
        HttpGet httpGet = null;
        try {
            CookieStore cookieStore = new BasicCookieStore();
            httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
            httpGet = new HttpGet(url);
            setGetHead(httpGet, headMap);
            httpClient.execute(httpGet);
            String JSESSIONID = null;
            List<Cookie> cookies = cookieStore.getCookies();
            for (int i = 0; i < cookies.size(); i++) {
                if (cookies.get(i).getName().equals("JSESSIONID-L")) {
                    JSESSIONID = cookies.get(i).getValue();
                    break;
                }
            }
            return JSESSIONID;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "";
    }


    public static String query(String jsessionId) {
        HttpClientUtil client = HttpClientUtil.getInstance();
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Cookie", "JSESSIONID-L=" + jsessionId);
        headers.put("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko");
        String content = client.httpGet("https://hn.122.gov.cn/drv/yycx/train/query", headers);
        return content;
    }

    public static String getTicketBySLL() throws KeyManagementException, NoSuchAlgorithmException, IOException {
        String body = "";

        //采用绕过验证的方式处理https请求
        SSLContext sslcontext = createIgnoreVerifySSL();

        //设置协议http和https对应的处理socket链接工厂的对象
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.INSTANCE)
                .register("https", new SSLConnectionSocketFactory(sslcontext))
                .build();
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        HttpClients.custom().setConnectionManager(connManager);


        //创建自定义的httpclient对象
        CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).build();
        //CloseableHttpClient client = HttpClients.createDefault();

        try {
            //创建get方式请求对象
            //String url = "https://127.0.0.1:53015/ia300";
            //Map<String, String> params = new HashMap<>();
            HttpPost post = new HttpPost("https://127.0.0.1:53015/ia300");

            //指定报文头Content-type、User-Agent
            post.setHeader("Content-type", "application/x-www-form-urlencoded");
            post.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:6.0.2) Gecko/20100101 Firefox/6.0.2");

            Map<String, String> paramsMap = new HashMap<>();
            String json = "{\"function\":\"IA300SHA1WithSeed\", \"Seed\":\"PLLJJAESTWCJKHRFRNJJZFTWXRRTHGCL\"}";
            paramsMap.put("json", json);
            if (paramsMap != null && paramsMap.size() > 0) {
                List<NameValuePair> nvps = new ArrayList<NameValuePair>();
                Set<String> keySet = paramsMap.keySet();
                for (String key : keySet) {
                    nvps.add(new BasicNameValuePair(key, paramsMap.get(key)));
                }
                post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
            }

            //执行请求操作，并拿到结果（同步阻塞）
            CloseableHttpResponse response = client.execute(post);

            //获取结果实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                //按指定编码转换结果实体为String类型
                body = EntityUtils.toString(entity, "UTF-8");
            }

            EntityUtils.consume(entity);
            //释放链接
            response.close();
            System.out.println("body:" + body);
        } finally {
            client.close();
        }
        return body;
    }


    public static void main(String[] args) throws Exception {
//        Calendar current = Calendar.getInstance();
//        Date endTimeDate = current.getTime();
//        String endTime = DateUtil.dateToString(endTimeDate, "yyyy-MM-dd");
//        System.out.println(endTime);
//        Date startTimeDate = DateUtils.addDays(endTimeDate, -20);
//        String startTime = DateUtil.dateToString(startTimeDate, "yyyy-MM-dd");
//        System.out.println(startTime);
//        String url = "https://hn.122.gov.cn/m/login?t=2";
//        Map<String, String> headers = new HashMap<>();
//        headers.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
//        headers.put("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36");
//        String jsessionId = HttpClientUtil.getInstance().getJSessionId(url, headers);
//        System.out.println("请求的jsessionId=================" + jsessionId);
//        String result = downloadVeriCode("d4a628da-3137-418c-b107-74bd4d478499");
//        System.out.println(result);
//        String vericode = HttpClientKeepSession.getVeriCode();
//        System.out.println(vericode);
//        String result1 = checkkey("d4a628da-3137-418c-b107-74bd4d478499", "81");
//        System.out.println(result1);

//        String result2 = getLoginTicket("PLLJJAESTWCJKHRFRNJJZFTWXRRTHGCL");
//        System.out.println(result2);


//        String result2 = checkLogin("20ded5a3-205a-4161-8f93-bb1f9989595f", "4b6647fc2af82deeff07fa2c55c8777ba3f20ebb", "7");
//        System.out.println(result2);

//        String result3 = query("c7679f26-946a-4830-ba81-fde0cf714fb3");
//        System.out.println(result3);

//        HttpClientUtil client = getInstance();
//        Map<String, String> params = new HashMap<String, String>();
//        params.put("memberId", "20");
//        client.uploadFileImpl("http://localhost:8080/DriverManage/web/examsubscribe/upload.htmls", "C:\\Users\\zengyao.ccc\\Downloads\\1.xls", "file", params);

//        Map<String, String> headers = new HashMap<String, String>();
//
//        headers.put("Cookie", "JSESSIONID-L=94b125dd-84cb-4279-aae6-13d6a420751b");

//        headers.put("Cookie", "multipart/form-data; boundary=---------------------------7b4a6d158c9");

//        Map<String, String> params = new HashMap<String, String>();

        //更新学员的图片信息
//        params.put("para1", "zzSxsDTZP4p3Bffr5nWHXY4AihZkKbX4");
//        params.put("submitted", "hello");
//        params.put("para2", "g8asj8ltkO5xNQ71ffRmH7ngzSyD5RrV8bkNg7ZrjmwVUqseZ4qwoCcVeharRaBTgbwDMTXD4Hr1TT9DT8pq6DvFccCmpjvOEuCpiJm9jh6XiSiP4i1ZPSFrvviJvArdhsG4DzyWkZgSO5mOuiaaqU87mnmyWdokj8MXDaBhdlk=");
//
//        String url = "http://hn.122.gov.cn/drv/sl/image/save?bz=2&wwlsh=243001809054782146&ticket=51966761853c05c48ea1b31a999f9c663dfb2da7";
//        client.uploadFileImpl(url, "C:\\2.JPG", "trackdata", params, headers);


//        params.put("sid", "54297dee2430e06cbea39dbbf1eb91c4");
//        String content = client.httpPost("http://hn.122.gov.cn/drv/sl/geneUsbKey", params, headers);
//        System.out.println("返回的内容========" + content);


//        params.put("type", "1");
//        params.put("ykrqstart", "2018-07-23");
//        params.put("ykrqend", "2018-08-23");
//        params.put("kskm", "");
//        params.put("kscx", "");
//        params.put("index", "1");
//        params.put("xm", "");
//        params.put("sfzmhm", "");
//        client.download("http://hn.122.gov.cn/drv/yycx/train/executedown", "C:\\Users\\zengyao.ccc\\Downloads\\1.xls", headers, params);


//        params.put("CSRQ", "1988-10-21");
//        params.put("DJZSXXDZ", "湖南省宁乡市煤炭坝镇双龙村马劲坳组");
//        params.put("DJZSXZQH", "430124");
//        params.put("DZYX", "");
//        params.put("GJ", "156");
//        params.put("JXMC", "");
//
//        params.put("LXDH", "");
//        params.put("LXZSXXDZ", "湖南省宁乡市煤炭坝镇双龙村马劲坳组");
//        params.put("LXZSXZQH", "430124");
//        params.put("LY", "A");
//        params.put("MODAL", "1");
//        params.put("SFZC2", "2");
//
//        params.put("SFZMHM", "430922198810218145");
//        params.put("SFZMMC", "A");
//        params.put("SFZYXQZ", "2028-06-08");
//        params.put("SJHM", "15344411968");
//        params.put("XB", "1");
//        params.put("XM", "高洁");
//
//        params.put("XZQH", "430100");
//        params.put("YJDZ", "湖南省宁乡市煤炭坝镇双龙村马劲坳组");
//        params.put("YZBM", "410001");
//        params.put("ZKCX", "C1");
//        params.put("ZZZM", "430922198810218145");
//        params.put("ZZZYXQZ", "");
//
//        params.put("TICKET", "640e9cf7c474a930e7bc7c46f9204f5c8dfe48aa");
//
//        String content = client.httpPost("http://hn.122.gov.cn/drv/sl/saveYyslxx", params, headers);
//        System.out.println("返回的内容========" + content);


//获取加密内容        ;
//        String content = client.httpPost("http://hn.122.gov.cn/m/doccamera/getencrypt", params, headers);
//        System.out.println("返回的内容========" + content);

//        params.put("rasdecrypt", "5QHeW2ZSymxFpDmiet7cc7xtXtFr7scF");
//        String content = client.httpPost("http://hn.122.gov.cn/m/doccamera/setdecrypt", params, headers);
//        System.out.println("返回的内容========" + content);
//        String xmlData = client.getXMLString();
//
//        client.sendXMLDataByPost("http://localhost:8080/drivermanage/wx/message/process.htmls", xmlData);

//        String url = "http://localhost:8080/drivermanage/wx/message/process.htmls";
//
//        HttpHeaders requestHeaders = new HttpHeaders();
//        requestHeaders.set("Accept", "application/xml");
//        requestHeaders.set("Content-Type", "application/xml;charset=UTF-8");


//        String xmlStr = "<xml>\n" +
//                "  <AppId><![CDATA[wx2421b1c4370ec43b]]></AppId>\n" +
//                "  <CreateTime><![CDATA[123456]]></CreateTime>\n" +
//                "  <InfoType><![CDATA[component_verify_ticket]]></InfoType>\n" +
//                "  <ComponentVerifyTicket><![CDATA[11111111]]></ComponentVerifyTicket>\n" +
//                "</xml>";
//
//        RestTemplate restTemplate = new RestTemplate();
//        org.springframework.http.HttpEntity<String> httpEntity = new org.springframework.http.HttpEntity<String>(xmlStr, requestHeaders);
//        String xmlData = restTemplate.postForObject(url, httpEntity, String.class);
//        System.out.println("返回的数据" + xmlData);
//        String url = "http://hn.122.gov.cn/drv/sl/print.pdf";
//
//        String jsessionId = RedisUtil.get("JESSIONID_" + 157);
//
//        Map<String, String> headers = new HashMap<String, String>();
//
//        headers.put("Cookie", "JSESSIONID-L=" + jsessionId);
//
//        Map<String, String> params = new HashMap<String, String>();
//
//        params.put("wwlsh", "243001901038700439");
//
//        client.download(url, "D:/243001901038700439.pdf", headers, params);

        HttpClientUtil client = getInstance();
        Map<String,String> headers = new HashMap<>();
        headers.put("Cookies","58tj_uuid=007c0180-4dbf-49e1-a41f-cc8c8da01ce7;new_uv=1;hpincode=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ7XCJjbGllbnRJcFwiOlwiMTEzLjI0Ny4xOC4xNjdcIixcImRldmljZUlkXCI6XCJcIixcImd5dWlkXCI6XCJcIixcImltZWlcIjpcIjFjMWY3OGY3OGQ1OTc2YzE5YTMwNWJmYWM1ZmZiZDNlMWQ3MjA1YjhcIixcImp4SWRcIjowLFwibG9naW5UaW1lXCI6MTYzMjk3MDE1ODk0MixcInVzZXJpZFwiOjM0MjA1NDg2MjY4MzAwNjU3MjF9IiwiaXNzIjoiSlhFRFQiLCJleHAiOjE2NjQwNzQxNTgsImlhdCI6MTYzMjk3MDE1OH0.Lv_QDEWErRu-N2B6hZ3EuffAown_QbdztRrvvqfmSPeBJ-aFQ_aEzlBkyv1yf0gabp2DNb5dKNtqcMoXrE1WCQ;userid=3420548626830065721");
        Map<String,String> params = new HashMap<>();
        client.download("https://wos.58cdn.com.cn/XyVuTsRqXyf/question/5eb4d75agw1e2917tah4oj.webp","D:/619_url.jpg",headers,params);
    }
}
